import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shen_nai/entity/device_entity.dart';
import 'package:shen_nai/eventbus/event_bus.dart';
import 'package:shen_nai/routes/app_routes.dart';
import 'package:shen_nai/socket/web_socket_manage.dart';

class DeviceItemView extends StatefulWidget {
  const DeviceItemView(this._entity, {Key? key}) : super(key: key);

  final DeviceEntity _entity;

  @override
  State<DeviceItemView> createState() => _DeviceItemViewState();
}

class _DeviceItemViewState extends State<DeviceItemView> {

  //是否展开
  bool isExpaned = false;
  //监听设备是否在线
  StreamSubscription? _subscription;

  @override
  void initState() {
    super.initState();
    WebSocketManage().subscription(widget._entity.number!);
    _subscription = eventBus.on<EquipmentInformationEvent>().listen((event) {
      if (widget._entity.number == event.data.serialNumber!) {
        log('event: ${event.data.serialNumber}');
        setState(() {
          widget._entity.isOnline = true;
        });
        _subscription?.cancel();
      }
    });
  }

  @override
  void dispose() {
    WebSocketManage().unSubscription(widget._entity.number!);
    _subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 15, right: 15, bottom: 10),
      child: Column(
        children: [
          Container(
            height: 36,
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
                borderRadius: isExpaned
                    ? const BorderRadius.vertical(top: Radius.circular(5))
                    : const BorderRadius.all(Radius.circular(5)),
                color: isExpaned
                    ? const Color(0xff3486F7)
                    : const Color(0xff3486F7).withOpacity(0.23)),
            child: InkWell(
              onTap: () {
                setState(() {
                  //isExpaned = !isExpaned;
                  Get.toNamed(AppRoute.DATA, arguments: widget._entity);
                });
              },
              child: Row(
                children: [
                  const SizedBox(
                    width: 11,
                  ),
                  Expanded(
                    child: Text(
                      '${widget._entity.name}${getTypeText()}',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: widget._entity.isOnline
                              ? Colors.white
                              : Colors.grey,
                          fontSize: 14),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  )
                ],
              ),
            ),
          ),
          !isExpaned
              ? const SizedBox()
              : Container(
                  decoration: BoxDecoration(
                      border:
                          Border.all(color: const Color(0xff4D4D4D), width: 1),
                      borderRadius: const BorderRadius.vertical(
                          bottom: Radius.circular(5))),
                  child: Column(
                    children: [
                      InkWell(
                        child: getSubItem(
                            widget._entity.sequence ?? '',
                            widget._entity.power1 ?? '0',
                            widget._entity.time1 ?? '0'),
                        onTap: () {
                          widget._entity.selectIndex = 0;
                          Get.toNamed(AppRoute.DATA, arguments: widget._entity);
                        },
                      ),
                      _getType(widget._entity.type ?? '0') == '2'
                          ? const Divider(
                              color: Color(0xff4D4D4D),
                              height: 1,
                            )
                          : const SizedBox(),
                      _getType(widget._entity.type ?? '0') == '2'
                          ? InkWell(
                              child: getSubItem(
                                  widget._entity.standby1 ?? '',
                                  widget._entity.power2 ?? '0',
                                  widget._entity.time2 ?? '0'),
                              onTap: () {
                                widget._entity.selectIndex = 1;
                                Get.toNamed(AppRoute.DATA,
                                    arguments: widget._entity);
                              },
                            )
                          : const SizedBox()
                    ],
                  ),
                )
        ],
      ),
    );
  }
  //文本格式化
  String getTypeText() {
    String text = '';
    if (widget._entity.type == '1') {
      if (widget._entity.sequence != '0') {
        text = '·${widget._entity.sequence}#炉';
      }
    } else if (widget._entity.type == '2') {
      text = '·${widget._entity.sequence}#炉 ${widget._entity.standby1}#炉 ';
    }
    return text;
  }
  //每一个item界面绘制
  Widget getSubItem(String sequence, String power, String time) {
    return Column(
      children: [
        const SizedBox(
          height: 10,
        ),
        Row(
          children: [
            const SizedBox(
              width: 10,
            ),
            Text(
              '$sequence#炉',
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold),
            ),
            const SizedBox(
              width: 6,
            ),
            Container(
              height: 8,
              width: 8,
              decoration: BoxDecoration(
                  color: widget._entity.isOnline
                      ? const Color(0xff72ED44)
                      : const Color(0xffA3A3A3),
                  borderRadius: const BorderRadius.all(Radius.circular(4))),
            ),
            const SizedBox(
              width: 6,
            ),
            int.parse(widget._entity.offLineDays ?? '0') == 0
                ? const SizedBox()
                : Text(
                    '${widget._entity.offLineDays}天',
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.bold),
                  ),
            const Expanded(child: SizedBox()),
            Image.asset(
              widget._entity.qualityIsBuy == 0
                  ? 'assets/images/cash_deposit_no.png'
                  : 'assets/images/cash_deposit.png',
              width: 14,
            ),
            (widget._entity.qualityIsBuy == 0 &&
                    int.parse(widget._entity.qualityDays ?? '0') > 0)
                ? Container(
                    margin: const EdgeInsets.only(left: 3, right: 10),
                    child: Text(widget._entity.qualityDays ?? '0',
                        style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold)),
                  )
                : const SizedBox(
                    width: 10,
                  )
          ],
        ),
        const SizedBox(
          height: 14,
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(
              width: 10,
            ),
            Expanded(
                child: Text.rich(TextSpan(children: [
              const TextSpan(
                  text: '累计时间：',
                  style: TextStyle(color: Colors.white, fontSize: 12)),
              TextSpan(
                  text: time,
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.bold))
            ]))),
            Expanded(
              child: Text.rich(TextSpan(children: [
                const TextSpan(
                    text: '累计电量：',
                    style: TextStyle(color: Colors.white, fontSize: 12)),
                TextSpan(
                    text: power,
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.bold))
              ])),
            ),
            const SizedBox(
              width: 10,
            )
          ],
        ),
        const SizedBox(
          height: 10,
        )
      ],
    );
  }

  //数量格式化
  String _getType(String type) {
    String str = type;
    int num = int.parse(type);
    if (num > 2) {
      str = '2';
    } else if (num < 1) {
      str = '1';
    }
    return str;
  }
}
